package club.gggd.security_jwt_demo.util;

import club.gggd.security_jwt_demo.pojo.module.DeviceType;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author:Lzq
 * @Date:2023/12/14
 */
public class UserAgentUtil {

    /**
     * 获取当前请求的User-Agent
     * @return
     */
    private static String getUserAgent() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            String header = request.getHeader("User-Agent");
            return header;
        }
        return null;
    }

    /**
     * 获取当前请求的设备
     * @return
     */
    public static String getDevice() {
        String userAgent = getUserAgent();
        if (userAgent == null) {
            return DeviceType.DEFAULT.getValue();
        }
        if (userAgent.toLowerCase().contains(DeviceType.ANDROID.getValue())) {
            return DeviceType.ANDROID.getValue();
        }
        if (userAgent.toLowerCase().contains("iphone") || userAgent.toLowerCase().contains("ipad")) {
            return DeviceType.IOS.getValue();
        }
        if (userAgent.toLowerCase().contains("windows nt") && !userAgent.toLowerCase().contains("windows phone")) {
            return DeviceType.PC.getValue();
        }
        return DeviceType.DEFAULT.getValue();
    }
}
